home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / graphic / jpegsrc4.zip / JDHUFF.C < prev    next >
C/C++ Source or Header  |  1992-12-03  |  13KB  |  417 lines

  1. /*
  2.  * jdhuff.c
  3.  *
  4.  * Copyright (C) 1991, 1992, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains Huffman entropy decoding routines.
  9.  * These routines are invoked via the methods entropy_decode
  10.  * and entropy_decode_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15.  
  16. /* Static variables to avoid passing 'round extra parameters */
  17.  
  18. static decompress_info_ptr dcinfo;
  19.  
  20. static INT32 get_buffer;    /* current bit-extraction buffer */
  21. static int bits_left;        /* # of unused bits in it */
  22. static boolean printed_eod;    /* flag to suppress multiple end-of-data msgs */
  23.  
  24. LOCAL void
  25. fix_huff_tbl (HUFF_TBL * htbl)
  26. /* Compute derived values for a Huffman table */
  27. {
  28.   int p, i, l, si;
  29.   char huffsize[257];
  30.   UINT16 huffcode[257];
  31.   UINT16 code;
  32.   
  33.   /* Figure C.1: make table of Huffman code length for each symbol */
  34.   /* Note that this is in code-length order. */
  35.  
  36.   p = 0;
  37.   for (l = 1; l <= 16; l++) {
  38.     for (i = 1; i <= (int) htbl->bits[l]; i++)
  39.       huffsize[p++] = (char) l;
  40.   }
  41.   huffsize[p] = 0;
  42.   
  43.   /* Figure C.2: generate the codes themselves */
  44.   /* Note that this is in code-length order. */
  45.   
  46.   code = 0;
  47.   si = huffsize[0];
  48.   p = 0;
  49.   while (huffsize[p]) {
  50.     while (((int) huffsize[p]) == si) {
  51.       huffcode[p++] = code;
  52.       code++;
  53.     }
  54.     code <<= 1;
  55.     si++;
  56.   }
  57.  
  58.   /* We don't bother to fill in the encoding tables ehufco[] and ehufsi[], */
  59.   /* since they are not used for decoding. */
  60.  
  61.   /* Figure F.15: generate decoding tables */
  62.  
  63.   p = 0;
  64.   for (l = 1; l <= 16; l++) {
  65.     if (htbl->bits[l]) {
  66.       htbl->valptr[l] = p;    /* huffval[] index of 1st sym of code len l */
  67.       htbl->mincode[l] = huffcode[p]; /* minimum code of length l */
  68.       p += htbl->bits[l];
  69.       htbl->maxcode[l] = huffcode[p-1];    /* maximum code of length l */
  70.     } else {
  71.       htbl->maxcode[l] = -1;
  72.     }
  73.   }
  74.   htbl->maxcode[17] = 0xFFFFFL;    /* ensures huff_DECODE terminates */
  75. }
  76.  
  77.  
  78. /*
  79.  * Code for extracting the next N bits from the input stream.
  80.  * (N never exceeds 15 for JPEG data.)
  81.  * This needs to go as fast as possible!
  82.  *
  83.  * We read source bytes into get_buffer and dole out bits as needed.
  84.  * If get_buffer already contains enough bits, they are fetched in-line
  85.  * by the macros get_bits() and get_bit().  When there aren't enough bits,
  86.  * fill_bit_buffer is called; it will attempt to fill get_buffer to the
  87.  * "high water mark", then extract the desired number of bits.  The idea,
  88.  * of course, is to minimize the function-call overhead cost of entering
  89.  * fill_bit_buffer.
  90.  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  91.  * of get_buffer to be used.  (On machines with wider words, an even larger
  92.  * buffer could be used.)  However, on some machines 32-bit shifts are
  93.  * relatively slow and take time proportional to the number of places shifted.
  94.  * (This is true with most PC compilers, for instance.)  In this case it may
  95.  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  96.  * average shift distance at the cost of more calls to fill_bit_buffer.
  97.  */
  98.  
  99. #ifdef SLOW_SHIFT_32
  100. #define MIN_GET_BITS  15    /* minimum allowable value */
  101. #else
  102. #define MIN_GET_BITS  25    /* max value for 32-bit get_buffer */
  103. #endif
  104.  
  105. static const int bmask[16] =    /* bmask[n] is mask for n rightmost bits */
  106.   { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  107.     0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  108.  
  109.  
  110. LOCAL int
  111. fill_bit_buffer (int nbits)
  112. /* Load up the bit buffer and do get_bits(nbits) */
  113. {
  114.   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  115.   while (bits_left < MIN_GET_BITS) {
  116.     register int c = JGETC(dcinfo);
  117.     
  118.     /* If it's 0xFF, check and discard stuffed zero byte */
  119.     if (c == 0xFF) {
  120.       int c2 = JGETC(dcinfo);
  121.       if (c2 != 0) {
  122.     /* Oops, it's actually a marker indicating end of compressed data. */
  123.     /* Better put it back for use later */
  124.     JUNGETC(c2,dcinfo);
  125.     JUNGETC(c,dcinfo);
  126.     /* There should be enough bits still left in the data segment; */
  127.     /* if so, just break out of the while loop. */
  128.     if (bits_left >= nbits)
  129.       break;
  130.     /* Uh-oh.  Report corrupted data to user and stuff zeroes into
  131.      * the data stream, so we can produce some kind of image.
  132.      * Note that this will be repeated for each byte demanded for the
  133.      * rest of the segment; this is a bit slow but not unreasonably so.
  134.      * The main thing is to avoid getting a zillion warnings, hence:
  135.      */
  136.     if (! printed_eod) {
  137.       WARNMS(dcinfo->emethods, "Corrupt JPEG data: premature end of data segment");
  138.       printed_eod = TRUE;
  139.     }
  140.     c = 0;            /* insert a zero byte into bit buffer */
  141.       }
  142.     }
  143.  
  144.     /* OK, load c into get_buffer */
  145.     get_buffer = (get_buffer << 8) | c;
  146.     bits_left += 8;
  147.   }
  148.  
  149.   /* Having filled get_buffer, extract desired bits (this simplifies macros) */
  150.   bits_left -= nbits;
  151.   return ((int) (get_buffer >> bits_left)) & bmask[nbits];
  152. }
  153.  
  154.  
  155. /* Macros to make things go at some speed! */
  156. /* NB: parameter to get_bits should be simple variable, not expression */
  157.  
  158. #define get_bits(nbits) \
  159.     (bits_left >= (nbits) ? \
  160.      ((int) (get_buffer >> (bits_left -= (nbits)))) & bmask[nbits] : \
  161.      fill_bit_buffer(nbits))
  162.  
  163. #define get_bit() \
  164.     (bits_left ? \
  165.      ((int) (get_buffer >> (--bits_left))) & 1 : \
  166.      fill_bit_buffer(1))
  167.  
  168.  
  169. /* Figure F.16: extract next coded symbol from input stream */
  170.   
  171. INLINE
  172. LOCAL int
  173. huff_DECODE (HUFF_TBL * htbl)
  174. {
  175.   register int l;
  176.   register INT32 code;
  177.   
  178.   code = get_bit();
  179.   l = 1;
  180.   while (code > htbl->maxcode[l]) {
  181.     code = (code << 1) | get_bit();
  182.     l++;
  183.   }
  184.  
  185.   /* With garbage input we may reach the sentinel value l = 17. */
  186.  
  187.   if (l > 16) {
  188.     WARNMS(dcinfo->emethods, "Corrupt JPEG data: bad Huffman code");
  189.     return 0;            /* fake a zero as the safest result */
  190.   }
  191.  
  192.   return htbl->huffval[ htbl->valptr[l] + ((int) (code - htbl->mincode[l])) ];
  193. }
  194.  
  195.  
  196. /* Figure F.12: extend sign bit */
  197.  
  198. #define huff_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  199.  
  200. static const int extend_test[16] =   /* entry n is 2**(n-1) */
  201.   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  202.     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  203.  
  204. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  205.   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  206.     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  207.     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  208.     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  209.  
  210.  
  211. /*
  212.  * Initialize for a Huffman-compressed scan.
  213.  * This is invoked after reading the SOS marker.
  214.  */
  215.  
  216. METHODDEF void
  217. huff_decoder_init (decompress_info_ptr cinfo)
  218. {
  219.   short ci;
  220.   jpeg_component_info * compptr;
  221.  
  222.   /* Initialize static variables */
  223.   dcinfo = cinfo;
  224.   bits_left = 0;
  225.   printed_eod = FALSE;
  226.  
  227.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  228.     compptr = cinfo->cur_comp_info[ci];
  229.     /* Make sure requested tables are present */
  230.     if (cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no] == NULL ||
  231.     cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no] == NULL)
  232.       ERREXIT(cinfo->emethods, "Use of undefined Huffman table");
  233.     /* Compute derived values for Huffman tables */
  234.     /* We may do this more than once for same table, but it's not a big deal */
  235.     fix_huff_tbl(cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no]);
  236.     fix_huff_tbl(cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
  237.     /* Initialize DC predictions to 0 */
  238.     cinfo->last_dc_val[ci] = 0;
  239.   }
  240.  
  241.   /* Initialize restart stuff */
  242.   cinfo->restarts_to_go = cinfo->restart_interval;
  243.   cinfo->next_restart_num = 0;
  244. }
  245.  
  246.  
  247. /*
  248.  * Check for a restart marker & resynchronize decoder.
  249.  */
  250.  
  251. LOCAL void
  252. process_restart (decompress_info_ptr cinfo)
  253. {
  254.   int c, nbytes;
  255.   short ci;
  256.  
  257.   /* Throw away any unused bits remaining in bit buffer */
  258.   nbytes = bits_left / 8;    /* count any full bytes loaded into buffer */
  259.   bits_left = 0;
  260.   p